#ifndef __CPPTUTORMEYERSSINGLETON_H__
#define __CPPTUTORMEYERSSINGLETON_H__

#include <exception>
#include <stdexcept>

using namespace std;

class Singleton
{
	private:
		// Create a new Singleton and store a
		// pointer to it in pInstance_
		static void Create()
		{
			// Task: initialize pInstance_
			static Singleton theInstance;
			pInstance_ = &theInstance;
		}
		// Gets called if dead reference detected
		static void OnDeadReference()
		{
			throw std::runtime_error("Dead Reference Detected");
		}
		virtual ~Singleton()
		{
			pInstance_ = 0;
			destroyed_ = true;
		}
		// Data
		static Singleton* pInstance_;
		static bool destroyed_;
		//... disabled 'tors/operator= ...
		Singleton();
		Singleton(const Singleton&);
		Singleton& operator=(const Singleton&);		
		
	public:
		Singleton& Instance()
		{
			if (!pInstance_)
			{
				// Check for dead reference
				// take a mutex lock here to make thread safe
				if (!pInstance_)
				{
					if (destroyed_)
					{
						OnDeadReference();
					}
					else
					{
						// First call—initialize
						Create();
					}
				}
			}
			return *pInstance_;
		}
};

#endif //__CPPTUTORMEYERSSINGLETON_H__
